<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Operation\Service;

use Doctrine\ORM\EntityManager;
use Laminas\Math\Rand;
use Operation\Entity\CouponCode;
use Operation\Entity\CouponCodeRule;

class CouponCodeManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 生成优惠码
     * @param CouponCodeRule $couponCodeRule
     * @param int $codeNum
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addCouponCode(CouponCodeRule $couponCodeRule, $codeNum = 0)
    {
        $codeNum = $codeNum > 0 ? $codeNum : $couponCodeRule->getCodeNum();

        $createTime = time();
        for ($i = 1; $i <= $codeNum; $i++) {
            $couponCode = new CouponCode();
            $couponCode->valuesSet([
                'couponCodeRuleId'  => $couponCodeRule->getCouponCodeRuleId(),
                'couponCodeStr'     => strtoupper(Rand::getString(8, 'abcdefghijklmnopqrstuvwxyz0123456789')),
                'couponCodeCreateTime' => $createTime
            ]);
            $this->entityManager->persist($couponCode);
        }
        $this->entityManager->flush();
    }

    /**
     * 更新优惠码信息
     * @param array $data
     * @param $couponCodeId
     */
    public function updateCouponCode(array $data, $couponCodeId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(CouponCode::class, 'c')
            ->set('c.userId', ':userId')->setParameter('userId', $data['userId'])
            ->set('c.userName', ':userName')->setParameter('userName', $data['userName'])
            ->set('c.orderId', ':orderId')->setParameter('orderId', $data['orderId'])
            ->set('c.orderSn', ':orderSn')->setParameter('orderSn', $data['orderSn'])
            ->set('c.couponCodeUseTime', ':couponCodeUseTime')->setParameter('couponCodeUseTime', time())
            ->where('c.couponCodeId = :couponCodeId')->setParameter('couponCodeId', $couponCodeId)
            ->andWhere('c.userId = 0');

        $qb->getQuery()->execute();
    }

    /**
     * 删除整个规则内的优惠码
     * @param $ruleId
     */
    public function deleteCouponAllCode($ruleId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(CouponCode::class, 'c')->where('c.couponCodeRuleId = :couponCodeRuleId')->setParameter('couponCodeRuleId', $ruleId);

        $qb->getQuery()->execute();
    }
}